package com.chengjue.transaction.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 描述:
 * 日志切面
 *
 * @author Kipeng Huang
 * @create 2018-02-27 下午1:36
 */
@Aspect
@Component
@Slf4j
public class LogAspect {
	@Pointcut("execution(public * com.chengjue.transaction.controller.*.*(..))")
	public void webLog() {
	}

	@Before("webLog()")
	public void doBefore(JoinPoint joinPoint) {
		// 接收到请求，记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		// 记录下请求内容
		log.info("URL :{}", request.getRequestURL().toString());
		log.info("HTTP_METHOD :{}", request.getMethod());
		log.info("IP :{}", request.getRemoteAddr());
		log.info("CLASS_METHOD :{}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
		log.info("ARGS :{}", Arrays.toString(joinPoint.getArgs()));
	}

	@AfterReturning(returning = "ret", pointcut = "webLog()")
	public void afterReturnning(Object ret) {

	}

	/**
	 * 后置异常通知
	 */
	@AfterThrowing("webLog()")
	public void throwss(JoinPoint jp) {
		log.info("方法异常时执行.....");
	}

	//后置最终通知,final增强，不管是抛出异常或者正常退出都会执行
	@After("webLog()")
	public void after(JoinPoint jp) {
		log.info("方法最后执行.....");
	}

	//环绕通知,环绕增强，相当于MethodInterceptor
	@Around("webLog()")
	public Object arround(ProceedingJoinPoint pjp) {
		log.info("方法环绕start.....");
		try {
			Object o = pjp.proceed();

			System.out.println("" + o);
			log.info("方法环绕proceed，结果是 :{}", o);
			return o;
		} catch (Throwable e) {
			e.printStackTrace();
			return null;
		}
	}


}
